<template>
  <div>
    <md-field-group>
      <!-- <van-button size="large" type="danger" :loading="isLogining" @click="loginSubmit" v-if="!this.$util.getLocalStorage('authToken')">授权登录</van-button> -->
      <van-button size="large" type="danger" :loading="isLogining" @click="loginSubmit">授权登录</van-button>
    </md-field-group>
    <div class="ver_text">
      <span>版本：{{version}}</span>
    </div>
  </div>
</template>

<script>
import fieldGroup from "@/vue/components/field-group/";

import { AUTH_URL, USER_LOGIN, USER_PROFILE } from "@/api/user";

import { VERSION } from "@/api/global";

export default {
  name: "login-request",

  data() {
    return {
      isLogining: false,
      version: VERSION
    };
  },
  created() {
    if (this.$route.query.code) {
      this.isLogining = true;
      this.$reqGet(USER_LOGIN, { code: this.$route.query.code })
        .then(res => {
          this.$util.setLocalStorage("authToken", res.data.authToken);
          this.saveUser(res.data.data);
          if (this.getUser().status === 9) {
            this.$router.replace({ name: "login-forbidden" });
            return;
          }
          this.$util.setLocalStorage("firstLogin", res.data.firstLogin);
          let redirect =
            this.$util.getSessionStorage("LoginRedirect") || this.getUri();
          //redirect: https://t.liyboo.com/wemall/
          location.replace(redirect);
        })
        .catch(err => {
          this.isLogining = false;
        });
    } else {
      this.loginSubmit();
    }
    
  },

  methods: {
    loginSubmit() {
      this.isLogining = true;
      const redirectUri = this.getUri() + this.$route.path.slice(1);
      //redirectUri: https://t.liyboo.com/wemall/login
      this.$reqGet(AUTH_URL, {
        redirectUri: redirectUri,
        state: "1"
      })
        .then(res => {
          window.location.href = res.data.data;
        })
        .catch(err => {
          this.isLogining = false;
        });
    },
    getLocalData(data) {
      if (!data) return {};
      return {
        avatar: data.avatar,
        user_id: data.user_id,
        background_image: data.background_image,
        nick_name: data.nick_name
      };
    }
  },

  components: {
    [fieldGroup.name]: fieldGroup
  }
};
</script>

<style lang="scss" scoped>
@import "../../assets/scss/mixin";

.register {
  padding-top: 40px;
  color: $font-color-gray;

  a {
    color: $font-color-gray;
  }

  > div {
    width: 50%;
    box-sizing: border-box;
    padding: 0 20px;
  }

  .connect {
    @include one-border(right);
    text-align: right;
  }
}

.ver_text {
  position: absolute;
  width: 100%;
  bottom: 20px;
  text-align: center;
  font-size: 8px;
  color: gray;
}
</style>
